<script setup>
import { ref, onMounted } from 'vue';
import { FilterMatchMode } from 'primevue/api';
import { useToast } from 'primevue/usetoast';
import axios from '../../util/interceptor';
import Toast from 'primevue/toast';
import instance from '../../util/interceptor';

onMounted(() => {
    getData();
    console.log(Roles)
});

const imageName = ref("");
const toast = useToast();
const dt = ref();
const Roles = ref();
const RoleDialog = ref(false);
const deleteRoleDialog = ref(false);
const deleteRolesDialog = ref(false);
const Role = ref({});
const selectedRoles = ref();
const selectedMenus = ref([])
const menus = ref();
const filters = ref({
    'global': { value: null, matchMode: FilterMatchMode.CONTAINS },
});
const submitted = ref(false);

//获取角色，菜单
const getData = async () => {
    const response = await axios.get("/permission/getPermission")
    console.log(response.data.data)
    const data = response.data.data
    if (response.data.code == 200) {
        Roles.value = data
    }
    const response2 = await axios.get("/menu/getMenus")
    console.log(response2.data.data)
    if (response2.data.code == 200) {
        menus.value = response2.data.data
    }
}

const openNew = () => {
    Role.value = {};
    submitted.value = false;
    RoleDialog.value = true;
};
const hideDialog = () => {
    RoleDialog.value = false;
    submitted.value = false;
    imageName.value = "new";
};

//保存角色
const saveRole = async () => {
    submitted.value = true;
    console.log(Role.value)
    if (!Role.value.deptName || !Role.value.menuIds) {
        console.log("gg")
        return;
    }
    const response = await axios.post("/permission/changePermission", Role.value)
    if (response.data.code == 200) {
        toast.add({ severity: 'success', summary: 'success', detail: response.data.message, life: 3000 })
        setTimeout(() => {
            location.reload();
        }, 1000)
    }
};

//打开编辑对话框
const editRole = (prod) => {
    Role.value = { ...prod };
    RoleDialog.value = true;
    selectedMenus.value = Role.value.menuIds;
    console.log(Role.value)
};
const confirmDeleteRole = (prod) => {
    Role.value = prod;
    deleteRoleDialog.value = true;
};

//删除角色
const deleteRole = async () => {
    console.log(Role.value.id)
    const response = await axios.post(`/dept/deleteDept/${Role.value.id}`)
    if (response.data.code == 200) {
        toast.add({ severity: 'success', summary: 'Successful', detail: response.data.message, life: 3000 });
        deleteRoleDialog.value = false;
        getData();
    }
};

//导出
const exportCSV = () => {
    dt.value.exportCSV();
};
const confirmDeleteSelected = () => {
    deleteRolesDialog.value = true;
};

//批量删除
const deleteSelectedRoles = async () => {
    const deleteRoles = Roles.value.filter(val => selectedRoles.value.includes(val));
    console.log(deleteRoles)
    const response = await axios.post("/dept/deleteDepts", deleteRoles)
    if (response.data.code == 200) {
        deleteRolesDialog.value = false;
        selectedRoles.value = null;
        toast.add({ severity: 'success', summary: 'Successful', detail: response.data.message, life: 3000 });
        setTimeout(() => {
            location.reload();
        }, 1000)
    }
};

</script>

<template>
    <div>
        <div class="card">
            <Toolbar class="mb-4">
                <template #start>
                    <Button label="新增" icon="pi pi-plus" severity="success" class="mr-2" @click="openNew" />
                    <Button label="删除" icon="pi pi-trash" severity="danger" @click="confirmDeleteSelected"
                        :disabled="!selectedRoles || !selectedRoles.length" />
                </template>

                <template #end>
                    <!-- <FileUpload mode="basic" accept="image/*" :maxFileSize="1000000" label="Import" chooseLabel="Import"
                        class="mr-2 inline-block" /> -->
                    <Button label="导出" icon="pi pi-upload" severity="help" @click="exportCSV($event)" />
                </template>
            </Toolbar>

            <DataTable ref="dt" :value="Roles" v-model:selection="selectedRoles" dataKey="id" :paginator="true"
                :rows="10" :filters="filters" removableSort
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rowsPerPageOptions="[5, 10, 25]" currentPageReportTemplate="第 {first} 到 {last} 条数据，共 {totalRecords} 角色">
                <template #header>
                    <div class="flex flex-wrap gap-2 align-items-center justify-content-between">
                        <h4 class="m-0">角色权限管理</h4>
                        <span class="p-input-icon-left">
                            <i class="pi pi-search" />
                            <InputText v-model="filters['global'].value" placeholder="搜索角色..." />
                        </span>
                    </div>
                </template>

                <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
                <!-- <Column field="code" header="Code" sortable style="min-width:12rem"></Column> -->
                <Column field="deptName" header="角色" sortable style="min-width:5rem"></Column>
                <Column header="权限" field="menuIds" style="min-width:6rem">
                    <template #body="slotProps">
                        <span v-for="category of slotProps.data.menus" :key="category.id">
                            <Tag>{{ category.menuName }}</Tag>
                            &nbsp;
                        </span>
                    </template>
                </Column>
                <Column :exportable="false" style="min-width:2rem">
                    <template #body="slotProps">
                        <Button icon="pi pi-pencil" outlined rounded @click="editRole(slotProps.data)" />
                        <Button icon="pi pi-trash" outlined rounded severity="danger"
                            @click="confirmDeleteRole(slotProps.data)" />
                    </template>
                </Column>
            </DataTable>
        </div>

        <Dialog v-model:visible="RoleDialog" :style="{ width: '450px' }" header="角色：" :modal="true" class="p-fluid">
            <div class="field">
                <label for="name">角色名称</label>
                <InputText id="name" v-model.trim="Role.deptName" required="true" autofocus
                    :class="{ 'p-invalid': submitted && !Role.deptName }" />
                <small class="p-error" v-if="submitted && !Role.deptName">请输入名称</small>
            </div>
            <div class="field">
                <label class="mb-3">权限菜单</label>
                <div class="formgrid grid">
                    <div class="field-radiobutton col-6" v-for="category of menus" :key="category.id">
                        <Checkbox v-model="Role.menuIds" :inputId="category.id" name="category" :value="category.id" />
                        <label :for="category.id">{{ category.menuName }}</label>
                    </div>
                </div>
                <small class="p-error" v-if="submitted && !Role.menuIds">未选择菜单</small>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="hideDialog" />
                <Button label="确定" icon="pi pi-check" text @click="saveRole" />
            </template>
        </Dialog>

        <Dialog v-model:visible="deleteRoleDialog" :style="{ width: '450px' }" header="Confirm" :modal="true">
            <div class="confirmation-content">
                <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
                <span v-if="Role">确定删除 <b>{{ Role.deptName }}</b>?</span>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteRoleDialog = false" />
                <Button label="确定" icon="pi pi-check" text @click="deleteRole" />
            </template>
        </Dialog>

        <Dialog v-model:visible="deleteRolesDialog" :style="{ width: '450px' }" header="Confirm" :modal="true">
            <div class="confirmation-content">
                <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
                <span v-if="Role">确定删除选中角色?</span>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="deleteRolesDialog = false" />
                <Button label="确定" icon="pi pi-check" text @click="deleteSelectedRoles" />
            </template>
        </Dialog>
        <Toast />
    </div>
</template>
